/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.commonutils.utils;


import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 获取请求头中的token
 *
 * @since 2022-02-17
 */
@Component
public class TokenUtil {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 从请求头中获取token,解析出uid
     *
     * @return uid
     */
    public String getUidFromHeader() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String authToken = request.getHeader(HttpHeaders.AUTHORIZATION).substring(this.tokenHead.length());
        return jwtTokenUtil.getUserIdFromToken(authToken);
    }

    /**
     * 从请求头中获取token,解析出userName
     *
     * @return userName
     */
    public String getUserNameFromHeader() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String authToken = request.getHeader(HttpHeaders.AUTHORIZATION).substring(this.tokenHead.length());
        return jwtTokenUtil.getUserNameFromToken(authToken);
    }
}
